package com.newcoin.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newcoin.admin.entity.*;
import com.newcoin.admin.mapper.*;
import com.newcoin.admin.service.AdminService;
import com.newcoin.admin.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private SysUsersMapper sysUsersMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private WithdrawMapper withdrawMapper;

    @Autowired
    private RechargeMapper rechargeReportMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private BonusMapper bonusMapper;

    @Autowired
    private FinancialProductMapper financialProductMapper;

    @Autowired
    private IndexAnnMapper indexAnnMapper;

    @Autowired
    private IndexCarouselMapper indexCarouselMapper;

    @Autowired
    private PayTheWayMapper payTheWayMapper;

    @Autowired
    private GradOrderTimeMapper gradOrderTimeMapper;

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private FirstChargeMapper firstChargeMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${filePath}")
    private String filePath;

    @Override
    public Result login(String username, String password, HttpSession session) throws Exception {
        log.info("username={},password={}", username, password);
        Result result = new Result();
        XgbSysUsers users = sysUsersMapper.selectOne(new QueryWrapper<XgbSysUsers>()
                .eq("username", username)
                .eq("password", DigestUtils.md5DigestAsHex(password.getBytes())));
        if (users == null) {
            result.setCode(500);
            result.setMessage("账号或密码错误");
            return result;
        }
        session.setAttribute("user", username);
        result.setCode(200);
        result.setMessage("登录成功");
        return result;
    }

    @Override
    public String index(Model model) throws Exception {
        Integer userCount = usersMapper.selectCount(new QueryWrapper<>());
        Integer userAddCount = usersMapper.selectCount(new QueryWrapper<XgbUsers>()
                .ge("reg_date", new SimpleDateFormat("YYYY-MM-dd").format(new Date()) + " 00:00:00"));
        Integer rechargeUnprocessedCount = rechargeReportMapper.selectCount(new QueryWrapper<XgbRecharge>());
        Integer withdrawUnprocessedCount = withdrawMapper.selectCount(new QueryWrapper<XgbWithdraw>()
                .eq("state", 0));
        BigDecimal totalRecharge = commonMapper.totalRecharge() == null ? new BigDecimal("0") : commonMapper.totalRecharge();
        BigDecimal totalWithdraw = commonMapper.totalWithdraw();
        model.addAttribute("userCount", userCount);
        model.addAttribute("userAddCount", userAddCount);
        model.addAttribute("rechargeUnprocessedCount", rechargeUnprocessedCount);
        model.addAttribute("withdrawUnprocessedCount", withdrawUnprocessedCount);
        model.addAttribute("totalRecharge", totalRecharge);
        model.addAttribute("totalWithdraw", totalWithdraw);
        return "index";
    }

    @Override
    public String getUsers(Model model, Long id, String mobile, Integer add, Integer type, String start, String end, Integer current) throws Exception {
        Page<XgbUsers> page = new Page<>();
        page.setCurrent(current);
        page.setSize(10L);
        QueryWrapper<XgbUsers> queryWrapper = new QueryWrapper<>();
        if (id != null) {
            queryWrapper.eq("id", id);
        }
        if (add != null) {
            queryWrapper.ge("reg_date",
                    new SimpleDateFormat("YYYY-MM-dd").format(new Date()) + " 00:00:00");
        }
        if (type != null) {
            switch (type) {
                case 0:
                    queryWrapper.eq("state", 1);
                    break;
                case 1:
                    queryWrapper.eq("state", 0);
                    break;
                case 2:
                    queryWrapper.eq("is_withdraw", 1);
                    break;
                case 3:
                    queryWrapper.eq("is_withdraw", 0);
                    break;
            }
        }
        if (!StringUtils.isEmpty(mobile)) {
            queryWrapper.eq("mobile", mobile);
        }
        if (!StringUtils.isEmpty(start)) {
            queryWrapper.ge("reg_date", start);
        }
        if (!StringUtils.isEmpty(end)) {
            queryWrapper.le("reg_date", end);
        }
        IPage<XgbUsers> iPage = usersMapper.selectPage(page, queryWrapper);
        model.addAttribute("current", iPage.getCurrent());
        model.addAttribute("totalPages", iPage.getPages());
        model.addAttribute("totalCount", iPage.getTotal());
        model.addAttribute("mobile", mobile);
        model.addAttribute("id", id);
        model.addAttribute("type", type);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("list", iPage.getRecords());
        return "users";
    }

    @Override
    public Result forbidOrLiftForbidWithdraw(Long id, Integer state) throws Exception {
        Result result = new Result();
        int row = usersMapper.update(null, new UpdateWrapper<XgbUsers>()
                .eq("id", id)
                .set("is_withdraw", state));
        if (row != 1) {
            result.setCode(500);
            result.setMessage("操作失败");
            return result;
        }
        result.setCode(200);
        result.setMessage("操作成功");
        return result;
    }

    @Override
    public Result forbidOrLiftForbidLogin(Long id, Integer state) throws Exception {
        Result result = new Result();
        int row = usersMapper.update(null, new UpdateWrapper<XgbUsers>()
                .eq("id", id)
                .set("state", state));
        if (row != 1) {
            result.setCode(500);
            result.setMessage("操作失败");
            return result;
        }
        redisTemplate.delete("token:" + id);
        result.setCode(200);
        result.setMessage("操作成功");
        return result;
    }

    @Override
    public Result editUser(Long id, Long pid, String mobile, String loginPwd, String payPwd, String path) throws Exception {
        log.info("id={},pid={},mobile={},loginPwd={},payPwd={},path={}",
                id, pid, mobile, loginPwd, payPwd, path);
        Result result = new Result();
        UpdateWrapper<XgbUsers> usersUpdateWrapper = new UpdateWrapper<>();
        usersUpdateWrapper.eq("id", id);
        usersUpdateWrapper.set("pid", pid);
        usersUpdateWrapper.set("mobile", mobile);
        if (!StringUtils.isEmpty(loginPwd)) {
            usersUpdateWrapper.set("login_pwd", DigestUtils.md5DigestAsHex(loginPwd.getBytes()));
        }
        if (!StringUtils.isEmpty(payPwd)) {
            usersUpdateWrapper.set("payPwd", DigestUtils.md5DigestAsHex(payPwd.getBytes()));
        }
        usersUpdateWrapper.set("path", path);
        int row = usersMapper.update(null, usersUpdateWrapper);
        if (row != 1) {
            result.setCode(500);
            result.setMessage("编辑失败");
            return result;
        }
        result.setCode(200);
        result.setMessage("成功");
        return result;
    }

    @Override
    public String outLogin(HttpSession session) throws Exception {
        session.removeAttribute("user");
        return "login";
    }

    @Override
    public String getRecharge(Model model, Integer current, String id, String mobile, String start, String end, Integer type) throws Exception {
        Page<XgbRecharge> page = new Page<>();
        page.setSize(10);
        page.setCurrent(current);
        Parameter parameter = new Parameter();
        if (!StringUtils.isEmpty(id)) {
            parameter.setId(id);
        }
        if (!StringUtils.isEmpty(mobile)) {
            parameter.setMobile(mobile);
        }
        if (!StringUtils.isEmpty(start)) {
            parameter.setStart(start);
        }
        if (!StringUtils.isEmpty(end)) {
            parameter.setEnd(end);
        }
        if (type != null) {
            switch (type) {
                case 0:
                    parameter.setState(0);
                    break;
                case 1:
                    parameter.setState(1);
                    break;
                case 2:
                    parameter.setState(2);
                    break;
            }
        }
        List<XgbRecharge> list = rechargeReportMapper.getRecharge(page, parameter);
        model.addAttribute("list", list);
        model.addAttribute("current", page.getCurrent());
        model.addAttribute("totalPages", page.getPages());
        model.addAttribute("totalCount", page.getTotal());
        model.addAttribute("id", id);
        model.addAttribute("mobile", mobile);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("type", type);
        return "recharge";
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result confirmRecharge(String id, Integer status) throws Exception {
        Result result = new Result();
        int row = rechargeReportMapper.update(null, new UpdateWrapper<XgbRecharge>()
                .eq("id", id)
                .set("status", status));
        if (row != 1) {
            result.setMessage("操作失败");
            result.setCode(500);
            return result;
        }
        if (status.compareTo(new Integer("1")) == 0) {
            XgbRecharge xgbRecharge = rechargeReportMapper.selectById(id);
            int r = accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                    .eq("user_id", xgbRecharge.getUserId())
                    .setSql("balance=balance+" + xgbRecharge.getAmount()));
            if (r != 1) {
                throw new RuntimeException("充值出错");
            }
            String path = rechargeReportMapper.getPath(id);
            if (!StringUtils.isEmpty(path)) {
                accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                        .setSql("team_total_recharge=team_total_recharge+" + xgbRecharge.getAmount())
                        .apply("user_id IN (" + path + ")"));
            }
            XgbFirstCharge firstCharge = firstChargeMapper.selectOne(new QueryWrapper<XgbFirstCharge>()
                    .eq("user_id", xgbRecharge.getUserId()));
            if (firstCharge == null) {
                firstCharge = new XgbFirstCharge();
                firstCharge.setAmount(xgbRecharge.getAmount());
                firstCharge.setUserId(xgbRecharge.getUserId());
                int rows = firstChargeMapper.insert(firstCharge);
                if (rows != 1) {
                    throw new RuntimeException("充值出错");
                }
            }
        }

        result.setMessage("成功");
        result.setCode(200);
        return result;
    }

    @Override
    public String getWithdrawal(Model model, Integer current, String id, String mobile, String start, String end, Integer type) throws Exception {
        Page<XgbWithdraw> page = new Page<>();
        page.setSize(10);
        page.setCurrent(current);
        Parameter parameter = new Parameter();
        if (!StringUtils.isEmpty(id)) {
            parameter.setId(id);
        }
        if (!StringUtils.isEmpty(mobile)) {
            parameter.setMobile(mobile);
        }
        if (!StringUtils.isEmpty(start)) {
            parameter.setStart(start);
        }
        if (!StringUtils.isEmpty(end)) {
            parameter.setEnd(end);
        }
        if (type != null) {
            parameter.setState(type);
        }
        List<XgbWithdraw> list = withdrawMapper.getWithdraw(page, parameter);
        model.addAttribute("list", list);
        model.addAttribute("current", page.getCurrent());
        model.addAttribute("totalPages", page.getPages());
        model.addAttribute("totalCount", page.getTotal());
        model.addAttribute("id", id);
        model.addAttribute("mobile", mobile);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("type", type);
        return "withdraw";
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result dealWith(String id) throws Exception {
        Result result = new Result();
        int row = withdrawMapper.update(null, new UpdateWrapper<XgbWithdraw>()
                .eq("id", id)
                .set("state", 1));
        if (row != 1) {
            result.setMessage("标记处理失败");
            result.setCode(500);
            return result;
        }
        XgbWithdraw withdraw = withdrawMapper.selectById(id);
        String path = withdrawMapper.getPath(id);
        System.out.println(path);
        if (!StringUtils.isEmpty(path)) {
            accountMapper.update(null, new UpdateWrapper<XgbAccount>()
//                    .setSql("team_run_water=team_run_water+" + withdraw.getAmount())
//                    .setSql("team_withdraw=team_withdraw+" + withdraw.getAmount())
                    .setSql("team_total_withdrawal=team_total_withdrawal+" + withdraw.getAmount())
                    .apply("user_id IN (" + path + ")"));
        }
        result.setMessage("标记处理成功");
        result.setCode(200);
        return result;
    }

    @Override
    public Result turnDown(String id, String content) throws Exception {
        Result result = new Result();
        int row = withdrawMapper.update(null, new UpdateWrapper<XgbWithdraw>()
                .eq("id", id)
                .set("state", 2)
                .set("reason", content));
        if (row != 1) {
            result.setMessage("驳回失败");
            result.setCode(500);
            return result;
        }
        XgbWithdraw withdraw = withdrawMapper.selectById(id);
        String path = withdrawMapper.getPath(id);
        if (!StringUtils.isEmpty(path)) {
            int r = accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                    /* .setSql("team_balance=team_balance+" + withdraw.getAmount().add(withdraw.getFee()))
                     .apply("user_id IN (" + path + ")"));
             int r = accountMapper.update(null, new UpdateWrapper<XgbAccount>()*/
                    .eq("user_id", withdraw.getUserId())
                    .setSql("balance=balance+" + withdraw.getAmount().add(withdraw.getFee())));
            if (r != 1) {
                throw new RuntimeException("驳回返余额出错");
            }
        }
        result.setMessage("驳回成功");
        result.setCode(200);
        return result;
    }

    @Override
    public String getGoods(Model model, Integer current, Integer priceStart, Integer priceEnd, String start, String end, Integer type) throws Exception {
        Page<XgbGoods> page = new Page<>();
        page.setCurrent(current);
        page.setSize(10);
        QueryWrapper<XgbGoods> queryWrapper = new QueryWrapper<>();
        if (priceStart != null) {
            queryWrapper.ge("goods_price", priceStart);
        }
        if (priceEnd != null) {
            queryWrapper.le("goods_price", priceEnd);
        }
        if (!StringUtils.isEmpty(start)) {
            queryWrapper.ge("create_date", start);
        }
        if (!StringUtils.isEmpty(end)) {
            queryWrapper.le("create_date", end);
        }
        if (type == null) {
            queryWrapper.orderByDesc("create_date");
        } else if (type != null) {
            switch (type) {
                case 0:
                    queryWrapper.orderByAsc("create_date");
                    break;
                case 1:
                    queryWrapper.orderByDesc("goods_price");
                    break;
                case 2:
                    queryWrapper.orderByAsc("goods_price");
                    break;
            }
        }
        IPage<XgbGoods> iPage = goodsMapper.selectPage(page, queryWrapper);
        model.addAttribute("list", iPage.getRecords());
        model.addAttribute("current", iPage.getCurrent());
        model.addAttribute("totalPages", iPage.getPages());
        model.addAttribute("totalCount", iPage.getTotal());
        model.addAttribute("priceStart", priceStart);
        model.addAttribute("priceEnd", priceEnd);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("type", type);
        return "goods";
    }

    @Override
    public Result editGood(Long id, String goodsName, BigDecimal goodsPrice, String goodsPic, BigDecimal proportion) throws Exception {
        Result result = new Result();
        UpdateWrapper<XgbGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        if (!StringUtils.isEmpty(goodsName)) {
            updateWrapper.set("goods_name", goodsName);
        }
        if (goodsPrice != null) {
            updateWrapper.set("goods_price", goodsPrice);
        }
        if (!StringUtils.isEmpty(goodsPic)) {
            updateWrapper.set("goods_pic", goodsPic);
        }
        if (proportion != null) {
            updateWrapper.set("proportion", proportion);
        }
        int row = goodsMapper.update(null, updateWrapper);
        if (row != 1) {
            result.setMessage("编辑失败");
            result.setCode(500);
            return result;
        }
        result.setMessage("编辑成功");
        result.setCode(200);
        return result;
    }

    @Override
    public Result addGood(String goodsName, BigDecimal goodsPrice, String goodsPic, BigDecimal proportion) throws Exception {
        Result result = new Result();
        XgbGoods xgbGoods = new XgbGoods();
        xgbGoods.setGoodsName(goodsName);
        xgbGoods.setGoodsPrice(goodsPrice);
        xgbGoods.setGoodsPic(goodsPic.substring(goodsPic.indexOf(":") + 1));
        xgbGoods.setProportion(proportion);
        int row = goodsMapper.insert(xgbGoods);
        if (row != 1) {
            result.setMessage("添加失败");
            result.setCode(500);
            return result;
        }
        result.setMessage("添加成功");
        result.setCode(200);
        return result;
    }

    @Override
    public String getVip(Model model, Integer level, String name) throws Exception {
        QueryWrapper<XgbVipLevel> queryWrapper = new QueryWrapper<>();
        if (level != null) {
            queryWrapper.eq("level", level);
        }
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        List<XgbVipLevel> vipLevels = vipMapper.selectList(queryWrapper);
        model.addAttribute("list", vipLevels);
        model.addAttribute("level", level);
        model.addAttribute("name", name);
        return "vip";
    }

    @Override
    public Result editVip(Integer id, String name, Integer level, BigDecimal amount, BigDecimal fee, BigDecimal max, Integer orderNum) throws Exception {
        Result result = new Result();
        UpdateWrapper<XgbVipLevel> xgbVipLevelUpdateWrapper = new UpdateWrapper<>();
        xgbVipLevelUpdateWrapper.eq("id", id);
        if (!StringUtils.isEmpty(name)) {
            xgbVipLevelUpdateWrapper.set("name", name);
        }
        if (level != null) {
            xgbVipLevelUpdateWrapper.set("level", level);
        }

        if (amount != null) {
            xgbVipLevelUpdateWrapper.set("amount", amount);
        }
        if (fee != null) {
            xgbVipLevelUpdateWrapper.set("fee", fee);
        }
        if (max != null) {
            xgbVipLevelUpdateWrapper.set("max", max);
        }
        if (orderNum != null) {
            xgbVipLevelUpdateWrapper.set("order_num", orderNum);
        }
        int row = vipMapper.update(null, xgbVipLevelUpdateWrapper);
        if (row != 1) {
            result.setCode(500);
            result.setMessage("编辑失败");
            return result;
        }
        result.setCode(200);
        result.setMessage("编辑成功");
        return result;
    }

    @Override
    public Result addVip(String name, Integer level, BigDecimal amount, BigDecimal fee, BigDecimal max, Integer orderNum) throws Exception {
        Result result = new Result();
        if (
                StringUtils.isEmpty(name) &&
                        level != null &&
                        amount != null &&
                        fee != null &&
                        max != null &&
                        orderNum != null

        ) {
            XgbVipLevel xgbVipLevel = new XgbVipLevel();
            xgbVipLevel.setName(name);
            xgbVipLevel.setLevel(level);
            xgbVipLevel.setAmount(amount);
            xgbVipLevel.setFee(fee);
            xgbVipLevel.setMax(max);
            xgbVipLevel.setOrderNum(orderNum);
            int row = vipMapper.insert(xgbVipLevel);
            if (row != 1) {
                result.setCode(500);
                result.setMessage("添加等级失败");
                return result;
            } else {
                result.setCode(200);
                result.setMessage("添加等级成功");
                return result;
            }
        }
        result.setCode(500);
        result.setMessage("所填字段不能有空");
        return result;
    }

    @Override
    public Result deleteVip(Integer id) throws Exception {
        Result result = new Result();
        int row = vipMapper.deleteById(id);
        if (row != 1) {
            result.setCode(500);
            result.setMessage("删除失败");
            return result;
        }
        result.setCode(200);
        result.setMessage("删除成功");
        return result;
    }

    @Override
    public String taskArea(Model model) throws Exception {
        List<XgbArea> areas = areaMapper.selectList(new QueryWrapper<>());
        model.addAttribute("list", areas);
        return "taskArea";
    }

    @Override
    public Result editTaskArea(Integer id, BigDecimal proportion, Integer levelCondition) throws Exception {
        Result result = new Result();
        if (proportion != null && levelCondition != null) {
            XgbArea xgbArea = new XgbArea();
            xgbArea.setId(id);
            xgbArea.setProportion(proportion);
            xgbArea.setLevelCondition(levelCondition);
            int row = areaMapper.updateById(xgbArea);
            if (row != 1) {
                result.setMessage("修改失败");
                result.setCode(500);
                return result;
            } else {
                result.setMessage("修改成功");
                result.setCode(200);
                return result;
            }
        }
        result.setMessage("所填字段不能为空");
        result.setCode(500);
        return result;
    }

    @Override
    public String bonus(Model model) throws Exception {
        List<XgbBonus> bonuses = bonusMapper.selectList(new QueryWrapper<>());
        model.addAttribute("list", bonuses);
        return "grabOrderBonus";
    }

    @Override
    public Result editBonus(Integer id, String name, BigDecimal proportion) throws Exception {
        Result result = new Result();
        if (!StringUtils.isEmpty(name) && proportion != null) {
            XgbBonus xgbBonus = new XgbBonus();
            xgbBonus.setId(id);
            xgbBonus.setName(name);
            xgbBonus.setProportion(proportion);
            int row = bonusMapper.updateById(xgbBonus);
            if (row != 1) {
                result.setMessage("修改失败");
                result.setCode(500);
                return result;
            } else {
                result.setMessage("修改成功");
                result.setCode(200);
                return result;
            }
        }
        result.setMessage("所填字段不能为空");
        result.setCode(500);
        return result;
    }

    @Override
    public String product(Model model) throws Exception {
        List<XgbFinancialProduct> finMEN = financialProductMapper.findAll();
        model.addAttribute("list", finMEN);
        return "product";
    }

    @Override
    public Result editProduct(Integer id, BigDecimal startAmount, BigDecimal endAmount, BigDecimal dailyReleaseRatio, Integer level) throws Exception {
        Result result = new Result();
        if (id != null &&
                startAmount != null &&
                endAmount != null &&
                dailyReleaseRatio != null &&
                level != null) {
            XgbFinancialProduct xgbFinancialProduct = new XgbFinancialProduct();
            xgbFinancialProduct.setId(id);
            xgbFinancialProduct.setStartAmount(startAmount);
            xgbFinancialProduct.setEndAmount(endAmount);
            xgbFinancialProduct.setDailyReleaseRatio(dailyReleaseRatio);
            xgbFinancialProduct.setLevel(level);
            int row = financialProductMapper.updateById(xgbFinancialProduct);
            if (row != 1) {
                result.setMessage("修改失败");
                result.setCode(500);
                return result;
            } else {
                result.setMessage("修改成功");
                result.setCode(200);
                return result;
            }
        }
        result.setMessage("所填字段不能为空");
        result.setCode(500);
        return result;
    }

    @Override
    public String ann(Model model, Integer current, String title, String start, String end, Integer type) throws Exception {
        Page<XgbIndexAnn> page = new Page<>();
        page.setSize(10);
        page.setCurrent(current);
        QueryWrapper<XgbIndexAnn> indexAnnQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(title)) {
            indexAnnQueryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(start)) {
            indexAnnQueryWrapper.ge("create_date", start);
        }
        if (!StringUtils.isEmpty(end)) {
            indexAnnQueryWrapper.le("create_date", end);
        }
        if (type != null) {
            indexAnnQueryWrapper.eq("state", type);
        }
        indexAnnQueryWrapper.orderByDesc("create_date");
        IPage<XgbIndexAnn> iPage = indexAnnMapper.selectPage(page, indexAnnQueryWrapper);
        model.addAttribute("list", iPage.getRecords());
        model.addAttribute("current", iPage.getCurrent());
        model.addAttribute("totalPages", iPage.getPages());
        model.addAttribute("totalCount", iPage.getTotal());
        model.addAttribute("title", title);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("type", type);
        return "ann";
    }

    @Override
    public Result addAnn(String title, String content) throws Exception {
        Result result = new Result();
        XgbIndexAnn xgbIndexAnn = new XgbIndexAnn();
        xgbIndexAnn.setTitle(title);
        xgbIndexAnn.setContent(content);
        int row = indexAnnMapper.insert(xgbIndexAnn);
        if (row != 1) {
            result.setCode(500);
            result.setMessage("添加失败");
            return result;
        }
        result.setCode(200);
        result.setMessage("添加成功");
        return result;
    }

    @Override
    public Result offShelf(String id) throws Exception {
        Result result = new Result();
        int row = indexAnnMapper.update(null, new UpdateWrapper<XgbIndexAnn>()
                .eq("id", id)
                .set("state", 1));
        if (row != 1) {
            result.setMessage("下架失败");
            result.setCode(500);
            return result;
        }
        result.setMessage("下架成功");
        result.setCode(200);
        return result;
    }

    @Override
    public Result editAnn(String id, String title, String content) throws Exception {
        Result result = new Result();
        if (!StringUtils.isEmpty(title) && !StringUtils.isEmpty(content)) {
            XgbIndexAnn xgbIndexAnn = new XgbIndexAnn();
            xgbIndexAnn.setContent(content);
            xgbIndexAnn.setTitle(title);
            xgbIndexAnn.setId(id);
            int row = indexAnnMapper.updateById(xgbIndexAnn);
            if (row != 1) {
                result.setMessage("修改失败");
                result.setCode(500);
                return result;
            } else {
                result.setMessage("修改成功");
                result.setCode(200);
                return result;
            }
        }
        result.setMessage("所填信息不能为空");
        result.setCode(500);
        return result;
    }

    @Override
    public String carousel(Model model) throws Exception {
        List<XgbIndexCarousel> indexCarousels = indexCarouselMapper.selectList(new QueryWrapper<>());
        model.addAttribute("list", indexCarousels);
        return "carousel";
    }

    @Override
    public Result addCarousel(MultipartFile file) throws Exception {
        Result result = new Result();
        if (file != null) {
            long fileName = System.currentTimeMillis();
            String originalFileName = file.getOriginalFilename();
            String suffix = originalFileName.substring(originalFileName.indexOf(".") + 1).toLowerCase();
            File file1 = new File(filePath + "carousel/" + fileName + "." + suffix);
            file.transferTo(file1);
            XgbIndexCarousel xgbIndexCarousel = new XgbIndexCarousel();
            xgbIndexCarousel.setUrl("/static/carousel/" + fileName + "." + suffix);
            int row = indexCarouselMapper.insert(xgbIndexCarousel);
            if (row != 1) {
                result.setCode(500);
                result.setMessage("新增出错");
                return result;
            } else {
                result.setCode(200);
                result.setMessage("新增成功");
                return result;
            }
        }
        result.setCode(500);
        result.setMessage("请选择有效文件");
        return result;
    }

    @Override
    public Result deleteCarousel(Integer id) throws Exception {
        Result result = new Result();
        int row = indexCarouselMapper.deleteById(id);
        if (row != 1) {
            result.setCode(500);
            result.setMessage("删除失败");
            return result;
        }
        result.setCode(200);
        result.setMessage("删除失败");
        return result;
    }

    @Override
    public String pay(Model model) throws Exception {
        List<XgbPayTheWay> list = payTheWayMapper.selectList(new QueryWrapper<>());
        model.addAttribute("list", list);
        return "pay";
    }

    @Override
    public Result editPay(Integer id, Integer type, String bankNum, String name, String info, MultipartFile file) throws Exception {
        Result result = new Result();
        if (type == 1) {
            if (!StringUtils.isEmpty(bankNum) && !StringUtils.isEmpty(name) && !StringUtils.isEmpty(info)) {
                XgbPayTheWay xgbPayTheWay = new XgbPayTheWay();
                xgbPayTheWay.setId(id);
                xgbPayTheWay.setType(type);
                xgbPayTheWay.setBankNum(bankNum);
                xgbPayTheWay.setName(name);
                xgbPayTheWay.setBankInfo(info);
                int row = payTheWayMapper.updateById(xgbPayTheWay);
                if (row != 1) {
                    result.setCode(500);
                    result.setMessage("修改失败");
                    return result;
                } else {
                    result.setCode(200);
                    result.setMessage("修改成功");
                    return result;
                }
            }
            result.setCode(500);
            result.setMessage("所填字段不能为空");
            return result;
        } else {
            if (file != null) {
                long fileName = System.currentTimeMillis();
                String originalFileName = file.getOriginalFilename();
                String suffix = originalFileName.substring(originalFileName.indexOf(".") + 1).toLowerCase();
                File file1 = new File(filePath + "pay/" + fileName + "." + suffix);
                file.transferTo(file1);
                XgbPayTheWay xgbPayTheWay = new XgbPayTheWay();
                xgbPayTheWay.setId(id);
                xgbPayTheWay.setType(type);
                xgbPayTheWay.setPayImg("/static/pay/" + fileName + "." + suffix);
                int row = payTheWayMapper.updateById(xgbPayTheWay);
                if (row != 1) {
                    result.setCode(500);
                    result.setMessage("修改失败");
                    return result;
                } else {
                    result.setCode(200);
                    result.setMessage("修改成功");
                    return result;
                }
            }
            result.setCode(500);
            result.setMessage("请选择有效文件");
            return result;
        }
    }

    @Override
    public String time(Model model) throws Exception {
        XgbGradOrderTime xgbGradOrderTime = gradOrderTimeMapper.selectOne(new QueryWrapper<>());
        model.addAttribute("start", xgbGradOrderTime.getTimeStart());
        model.addAttribute("end", xgbGradOrderTime.getTimeEnd());
        model.addAttribute("id", xgbGradOrderTime.getId());
        return "time";
    }

    @Override
    public Result save(Integer id, String start, String end) throws Exception {
        Result result = new Result();
        XgbGradOrderTime xgbGradOrderTime = new XgbGradOrderTime();
        xgbGradOrderTime.setId(id);
        xgbGradOrderTime.setTimeStart(start);
        xgbGradOrderTime.setTimeEnd(end);
        int row = gradOrderTimeMapper.updateById(xgbGradOrderTime);
        if (row != 1) {
            result.setMessage("保存失败");
            result.setCode(500);
            return result;
        }
        result.setMessage("保存成功");
        result.setCode(200);
        return result;
    }

    @Override
    public void exportExcel(HttpServletResponse response, Integer current, String id, String mobile, String start, String end, Integer type) throws Exception {
        Page<XgbWithdraw> page = new Page<>();
        page.setSize(10);
        page.setCurrent(current);
        Parameter parameter = new Parameter();
        if (!StringUtils.isEmpty(id)) {
            parameter.setId(id);
        }
        if (!StringUtils.isEmpty(mobile)) {
            parameter.setMobile(mobile);
        }
        if (!StringUtils.isEmpty(start)) {
            parameter.setStart(start);
        }
        if (!StringUtils.isEmpty(end)) {
            parameter.setEnd(end);
        }
        if (type != null) {
            parameter.setState(type);
        }
        List<XgbWithdraw> list = withdrawMapper.getWithdraw(page, parameter);
        ExcelUtil.exportExcel(response, list);
    }

    @Override
    public String app(Model model) throws Exception {
        NewCoinAppVersion xgbAppVersion = commonMapper.getAppVersionInfo();
        model.addAttribute("version", xgbAppVersion.getVersion());
        model.addAttribute("wGetUrl", xgbAppVersion.getWgetUrl());
        model.addAttribute("appUrl", xgbAppVersion.getAppUrl());
        model.addAttribute("status", xgbAppVersion.getStatus());
        model.addAttribute("remark", xgbAppVersion.getRemark());
        return "app";
    }

    @Override
    public Result editApp(String version, String appUrl, String wGetUrl, Integer status, String remark) throws Exception {
        Result result = new Result();
        if (StringUtils.isEmpty(version)) {
            result.setMessage("版本号不能为空");
            result.setCode(500);
            return result;
        }
        if (StringUtils.isEmpty(appUrl)) {
            result.setMessage("整包下载地址不能为空");
            result.setCode(500);
            return result;
        }
        if (StringUtils.isEmpty(wGetUrl)) {
            result.setMessage("热更新下载地址不能为空");
            result.setCode(500);
            return result;
        }
        int row = commonMapper.updateAppVersion(version, wGetUrl, appUrl, status, remark);
        if (row != 1) {
            result.setMessage("提交失败");
            result.setCode(500);
            return result;
        }
        result.setMessage("提交成功");
        result.setCode(200);
        return result;
    }


}
